﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotNet.Practico1.DataAccess;
using DotNet.Practico1.UI.Model;
using DotNet.Practico1.UI.Support;
using System.Drawing;
using System.Data.Objects;
using System.IO;

namespace DotNet.Practico1.UI.Presentation
{
    public class MainPresenter
    {
        private IMainView _view;

        public MainPresenter(IMainView view)
        {
            this._view = view;
        }

        #region Public Methods

        public void Load()
        {
            try
            {
                using (DotNetPractico1Entities data = new DotNetPractico1Entities())
                {
                    this._view.PhoneTypes = (from phoneType in data.PhoneTypes
                                             select new TypesDTO()
                                             {
                                                 Value = phoneType.Id,
                                                 Text = phoneType.Description
                                             }).ToList();
                    this._view.EmailTypes = (from emailType in data.EmailTypes
                                             select new TypesDTO()
                                             {
                                                 Value = emailType.Id,
                                                 Text = emailType.Description
                                             }).ToList();
                    this._view.AddressTypes = (from addressType in data.AddressTypes
                                               select new TypesDTO()
                                             {
                                                 Value = addressType.Id,
                                                 Text = addressType.Description
                                             }).ToList();

                    this._view.Groups = (from g in data.Groups
                                         select new TypesDTO()
                                         {
                                             Value = g.Id,
                                             Text = g.Name
                                         }).ToList();

                    this._view.ContactGroups = (from g in data.Groups
                                                select new TypesDTO()
                                                {
                                                    Value = g.Id,
                                                    Text = g.Name
                                                }).ToList();

                    this._view.LoadFields();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void GetContacts()
        {
            using (DotNetPractico1Entities data = new DotNetPractico1Entities())
            {
                var contacts = (from contact in data.Contacts
                                orderby contact.LastName, contact.FirstName descending
                                select new UIContact()
                                {
                                    BirthDate = contact.BirthDate,
                                    Comments = contact.Comments,
                                    FirstName = contact.FirstName,
                                    LastName = contact.LastName,
                                    Picture = contact.Picture,
                                    Id = contact.Id
                                });

                this._view.Contacts = contacts;
            }
        }

        public void GetContactsByPhone()
        {
            if (this._view.SearchPhoneType != -1 && this._view.SearchPhone != String.Empty)
            {
                using (DotNetPractico1Entities data = new DotNetPractico1Entities())
                {
                    this._view.FoundContacts = (from contact in data.Contacts
                                                join phone in data.Phones
                                                    on contact.Id equals phone.IdContact
                                                where phone.idType == this._view.SearchPhoneType &&
                                                    phone.Number == this._view.SearchPhone
                                                orderby contact.LastName, contact.FirstName descending
                                                select new UIContact()
                                                {
                                                    BirthDate = contact.BirthDate,
                                                    Comments = contact.Comments,
                                                    FirstName = contact.FirstName,
                                                    LastName = contact.LastName,
                                                    Picture = contact.Picture,
                                                    Id = contact.Id
                                                }).ToList();
                    this._view.UpdateFoundContacts();
                }
            }
            else
            {
                Utils.DisplayError("Se debe ingresar un número y tipo de teléfono para buscar.");
            }
        }

        public void GetContactByIdForSearch()
        {
            if (this._view.SelectedContactId != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var contactData = (from contact in data.Contacts
                                       where contact.Id == this._view.SelectedContactId
                                       select contact).Single();


                    this._view.FoundContactFirstName = contactData.FirstName;
                    this._view.FoundContactLastName = contactData.LastName;
                    this._view.FoundContactBirthDate = contactData.BirthDate;
                    this._view.FoundContactComments = contactData.Comments;
                    this._view.FoundContactImage = contactData.Picture;

                    this._view.FoundAddresses = (from address in contactData.Addresses
                                                 select new UIAddress()
                                                 {
                                                     AddressTypeId = address.AddressType.Id,
                                                     AddressType = address.AddressType.Description,
                                                     Address = address.Address1,
                                                     City = address.City,
                                                     Country = address.Country,
                                                     PostalCode = address.PostalCode
                                                 }).ToList();
                    this._view.FoundEmails = (from email in contactData.Emails
                                              select new UIEmail()
                                              {
                                                  EmailAddress = email.Email1,
                                                  EmailType = email.EmailType.Description,
                                                  EmailTypeId = email.EmailType.Id
                                              }).ToList();
                    this._view.FoundPhones = (from phone in contactData.Phones
                                              select new UIPhone()
                                              {
                                                  PhoneNumber = phone.Number,
                                                  PhoneType = phone.PhoneType.Description,
                                                  PhoneTypeId = phone.PhoneType.Id
                                              }).ToList();
                    this._view.FoundGroups = (from g in contactData.Groups
                                              select new UIGroup()
                                              {
                                                  GroupId = g.Id,
                                                  GroupName = g.Name,
                                                  MemberCount = g.Contacts.Count
                                              }).ToList();

                    this._view.UpdateFoundAddresses();
                    this._view.UpdateFoundEmails();
                    this._view.UpdateFoundPhones();
                    this._view.UpdateFoundGroups();
                }
            }
        }
        public void GetContactByIdForInfo()
        {
            if (this._view.SelectedInfoContactId != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var contactData = (from contact in data.Contacts
                                       where contact.Id == this._view.SelectedInfoContactId
                                       select contact).Single();


                    this._view.InfoContactFirstName = contactData.FirstName;
                    this._view.InfoContactLastName = contactData.LastName;
                    this._view.InfoContactBirthDate = contactData.BirthDate;
                    this._view.InfoContactComments = contactData.Comments;
                    this._view.InfoContactImage = contactData.Picture;

                    this._view.InfoAddresses = (from address in contactData.Addresses
                                                select new UIAddress()
                                                {
                                                    AddressTypeId = address.AddressType.Id,
                                                    AddressType = address.AddressType.Description,
                                                    Address = address.Address1,
                                                    City = address.City,
                                                    Country = address.Country,
                                                    PostalCode = address.PostalCode
                                                }).ToList();
                    this._view.InfoEmails = (from email in contactData.Emails
                                             select new UIEmail()
                                             {
                                                 EmailAddress = email.Email1,
                                                 EmailType = email.EmailType.Description,
                                                 EmailTypeId = email.EmailType.Id
                                             }).ToList();
                    this._view.InfoPhones = (from phone in contactData.Phones
                                             select new UIPhone()
                                             {
                                                 PhoneNumber = phone.Number,
                                                 PhoneType = phone.PhoneType.Description,
                                                 PhoneTypeId = phone.PhoneType.Id
                                             }).ToList();
                    this._view.InfoGroups = (from g in contactData.Groups
                                             select new UIGroup()
                                             {
                                                 GroupId = g.Id,
                                                 GroupName = g.Name,
                                                 MemberCount = g.Contacts.Count
                                             }).ToList();

                    this._view.UpdateInfoAddresses();
                    this._view.UpdateInfoEmails();
                    this._view.UpdateInfoPhones();
                    this._view.UpdateInfoGroups();
                }
            }
        }

        public void SaveContact()
        {
            if (this._view.InfoContactFirstName != String.Empty && this._view.InfoContactLastName != String.Empty)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    if (this._view.SelectedInfoContactId == -1)
                    {
                        var contact = new Contact()
                        {
                            BirthDate = this._view.InfoContactBirthDate,
                            Comments = this._view.InfoContactComments,
                            FirstName = this._view.InfoContactFirstName,
                            LastName = this._view.InfoContactLastName,
                            Picture = this._view.InfoContactImage
                        };
                        if (this._view.SelectedGroup != -1)
                        {
                            var grp = (from g in data.Groups
                                       where g.Id == this._view.SelectedGroup
                                       select g).Single();

                            contact.Groups.Add(grp);
                        }

                        data.Contacts.AddObject(contact);
                        data.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
                        this._view.SelectedInfoContactId = contact.Id;
                        this.EnableContactInfoLinks();
                    }
                    else
                    {
                        var contact = (from c in data.Contacts
                                       where c.Id == this._view.SelectedInfoContactId
                                       select c).Single();

                        contact.BirthDate = this._view.InfoContactBirthDate;
                        contact.Comments = this._view.InfoContactComments;
                        contact.FirstName = this._view.InfoContactFirstName;
                        contact.LastName = this._view.InfoContactLastName;
                        contact.Picture = this._view.InfoContactImage;
                        data.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
                    }


                }
            }
            else
            {
                Utils.DisplayError("Se debe ingresar el nombre y apellido para guardar el contacto.");
            }
        }

        public void GetContactByNames()
        {
            if (this._view.SearchFirstName != String.Empty || this._view.SearchLastName != String.Empty)
            {
                using (DotNetPractico1Entities data = new DotNetPractico1Entities())
                {
                    this._view.FoundContacts = (from contact in data.Contacts
                                                where contact.FirstName.Contains(this._view.SearchFirstName) ||
                                                contact.LastName.Contains(this._view.SearchLastName)
                                                orderby contact.LastName, contact.FirstName descending
                                                select new UIContact()
                                                {
                                                    BirthDate = contact.BirthDate,
                                                    Comments = contact.Comments,
                                                    FirstName = contact.FirstName,
                                                    LastName = contact.LastName,
                                                    Picture = contact.Picture,
                                                    Id = contact.Id
                                                }).ToList();
                    this._view.UpdateFoundContacts();
                }
            }
            else
            {
                Utils.DisplayError("Se debe ingresar por lo menos parte del nombre o apellido para buscar.");
            }
        }

        public void GetContactByBirthDate()
        {
            if (this._view.SearchStartDate != null && this._view.SearchEndDate != null)
            {
                using (DotNetPractico1Entities data = new DotNetPractico1Entities())
                {

                    this._view.FoundContacts = (from contact in data.GetConactsByBirthDate(this._view.SearchStartDate, this._view.SearchEndDate)
                                                orderby contact.LastName, contact.FirstName descending
                                                select new UIContact()
                                                {
                                                    BirthDate = contact.BirthDate,
                                                    Comments = contact.Comments,
                                                    FirstName = contact.FirstName,
                                                    LastName = contact.LastName,
                                                    Picture = contact.Picture,
                                                    Id = contact.Id
                                                }).ToList();
                    this._view.UpdateFoundContacts();
                }
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar una opción para buscar por cumpleaños.");
            }
        }

        public void GetContactByEmail()
        {
            if (this._view.SearchEmailType != -1 && this._view.SearchEmail != String.Empty)
            {
                using (DotNetPractico1Entities data = new DotNetPractico1Entities())
                {

                    this._view.FoundContacts = (from contact in data.Contacts
                                                join email in data.Emails
                                                    on contact.Id equals email.IdContact
                                                where email.EmailType.Id == this._view.SearchEmailType &&
                                                    email.Email1 == this._view.SearchEmail
                                                orderby contact.LastName, contact.FirstName descending
                                                select new UIContact()
                                                {
                                                    BirthDate = contact.BirthDate,
                                                    Comments = contact.Comments,
                                                    FirstName = contact.FirstName,
                                                    LastName = contact.LastName,
                                                    Picture = contact.Picture,
                                                    Id = contact.Id
                                                }).ToList();
                    this._view.UpdateFoundContacts();
                }
            }
            else
            {
                Utils.DisplayError("Se debe ingresar una dirección y tipo de email para buscar.");
            }
        }

        public void GetContactsByGroup()
        {
            if (this._view.SelectedGroup != -1)
            {
                using (DotNetPractico1Entities data = new DotNetPractico1Entities())
                {

                    this._view.Contacts = (from grp in data.Groups
                                           from contact in grp.Contacts
                                           where grp.Id == this._view.SelectedGroup
                                           select new UIContact()
                                           {
                                               BirthDate = contact.BirthDate,
                                               Comments = contact.Comments,
                                               FirstName = contact.FirstName,
                                               LastName = contact.LastName,
                                               Picture = contact.Picture,
                                               Id = contact.Id
                                           }).ToList();

                    this._view.UpdateContacts();
                }
            }
        }

        public void GetGrouplessContacts()
        {
            using (DotNetPractico1Entities data = new DotNetPractico1Entities())
            {

                this._view.Contacts = (from contact in data.Contacts
                                       where contact.Groups.Count == 0
                                       select new UIContact()
                                       {
                                           BirthDate = contact.BirthDate,
                                           Comments = contact.Comments,
                                           FirstName = contact.FirstName,
                                           LastName = contact.LastName,
                                           Picture = contact.Picture,
                                           Id = contact.Id
                                       }).ToList();

                this._view.UpdateContacts();
                this._view.SelectedGroup = -1;
                this._view.SelectedInfoContactId = -1;
            }
        }

        public void GetAllContacts()
        {
            using (DotNetPractico1Entities data = new DotNetPractico1Entities())
            {

                this._view.Contacts = (from contact in data.Contacts
                                       select new UIContact()
                                       {
                                           BirthDate = contact.BirthDate,
                                           Comments = contact.Comments,
                                           FirstName = contact.FirstName,
                                           LastName = contact.LastName,
                                           Picture = contact.Picture,
                                           Id = contact.Id
                                       }).ToList();

                this._view.UpdateContacts();
                this._view.SelectedGroup = -1;
                this._view.SelectedInfoContactId = -1;
            }
        }


        public void DisplaySelectedFoundAddress()
        {
            if (this._view.FoundAddress != null)
            {
                this._view.FoundAddressStreet = this._view.FoundAddress.Address;
                this._view.FoundAddressCity = this._view.FoundAddress.City;
                this._view.FoundAddressPostalCode = this._view.FoundAddress.PostalCode;
                this._view.FoundAddressCountry = this._view.FoundAddress.Country;
            }
        }
        public void DisplaySelectedFoundPhone()
        {
            if (this._view.FoundPhone != null)
            {
                this._view.FoundPhoneNumber = this._view.FoundPhone.PhoneNumber;
                this._view.FoundPhoneType = this._view.FoundPhone.PhoneType;
            }
        }
        public void DisplaySelectedFoundEmails()
        {
            if (this._view.FoundEmail != null)
            {
                this._view.FoundEmailAddress = this._view.FoundEmail.EmailAddress;
                this._view.FoundEmailType = this._view.FoundEmail.EmailType;
            }
        }
        public void DisplaySelectedFoundGroups()
        {
            if (this._view.FoundGroup != null)
            {
                this._view.FoundGroupMemberCount = this._view.FoundGroup.MemberCount.ToString();
            }
        }


        public void DisplaySelectedInfoAddress()
        {
            if (this._view.InfoAddress != null)
            {
                this._view.InfoAddressStreet = this._view.InfoAddress.Address;
                this._view.InfoAddressCity = this._view.InfoAddress.City;
                this._view.InfoAddressPostalCode = this._view.InfoAddress.PostalCode;
                this._view.InfoAddressCountry = this._view.InfoAddress.Country;
                this._view.InfoAddressType = this._view.InfoAddress.AddressTypeId;
            }
        }
        public void DisplaySelectedInfoPhone()
        {
            if (this._view.InfoPhone != null)
            {
                this._view.InfoPhoneNumber = this._view.InfoPhone.PhoneNumber;
                this._view.InfoPhoneType = this._view.InfoPhone.PhoneTypeId;
            }
        }
        public void DisplaySelectedInfoEmails()
        {
            if (this._view.InfoEmail != null)
            {
                this._view.InfoEmailAddress = this._view.InfoEmail.EmailAddress;
                this._view.InfoEmailType = this._view.InfoEmail.EmailTypeId;
            }
        }
        public void DisplaySelectedInfoGroups()
        {
            if (this._view.InfoGroup != null)
            {
                this._view.SelectedInfoGroup = this._view.InfoGroup.GroupId;
                this._view.InfoGroupMemberCount = this._view.InfoGroup.MemberCount.ToString();
            }
        }

        public void SwitchToModifyUser()
        {
            if (this._view.SelectedContactId != null)
            {
                SwitchToInfoTab();
                this._view.InfoContactFirstName = this._view.FoundContact.FirstName;
                this._view.InfoContactBirthDate = this._view.FoundContact.BirthDate;
                this._view.InfoContactComments = this._view.FoundContact.Comments;
                this._view.InfoContactLastName = this._view.FoundContact.LastName;
                this._view.InfoContactImage = this._view.FoundContact.Picture;

                this._view.InfoAddresses = this._view.FoundAddresses;
                this._view.InfoEmails = this._view.FoundEmails;
                this._view.InfoPhones = this._view.FoundPhones;
                this._view.InfoGroups = this._view.FoundGroups;

                this._view.UpdateInfoAddresses();
                this._view.UpdateInfoEmails();
                this._view.UpdateInfoGroups();
                this._view.UpdateInfoPhones();
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar un contacto para modificar.");
            }
        }

        public void SwitchToSearchTab()
        {
            this._view.ShowSearchPanel = true;
            this._view.ShowInfoPanel = false;
            this._view.BoldSearchButton();
        }

        public void SwitchToInfoTab()
        {
            this._view.ShowSearchPanel = false;
            this._view.ShowInfoPanel = true;
            this._view.BoldInfoButton();
        }
        public void SetContactImage()
        {
            this._view.InfoContactImage = Utils.ImageToBinary(Image.FromFile(this._view.ImagePath));
        }

        #endregion

        public void AddAddress()
        {
            if (this._view.InfoAddressStreet != String.Empty && this._view.InfoAddressType != -1 &&
                this._view.InfoAddressCity != String.Empty && this._view.InfoAddressCountry != String.Empty &&
                this._view.InfoAddressPostalCode != String.Empty)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var newAddress = new Address()
                    {
                        Address1 = this._view.InfoAddressStreet,
                        IdType = this._view.InfoAddressType,
                        City = this._view.InfoAddressCity,
                        Country = this._view.InfoAddressCountry,
                        PostalCode = this._view.InfoAddressPostalCode,
                        IdContact = this._view.SelectedContactId
                    };

                    data.Addresses.AddObject(newAddress);
                    data.SaveChanges();
                }
            }
            else
            {
                Utils.DisplayError("Todos los datos de dirección son requeridos.");
            }
        }
        public void EditAddress()
        {
            if (this._view.InfoAddressType != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var address = (from add in data.Addresses
                                   where add.IdContact == this._view.SelectedContactId &&
                                   add.IdType == this._view.InfoAddressType
                                   select add).Single();

                    address.Address1 = this._view.InfoAddressStreet;
                    address.IdType = this._view.InfoAddressType;
                    address.City = this._view.InfoAddressCity;
                    address.Country = this._view.InfoAddressCountry;
                    address.PostalCode = this._view.InfoAddressPostalCode;

                    data.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                }
            }
            else
            {
                Utils.DisplayError("Debe seleccionar una dirección para modificar.");
            }
        }

        public void AddPhone()
        {
            if (this._view.InfoAddressType != -1 && this._view.InfoPhoneNumber != String.Empty)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var newPhone = new Phone()
                    {
                        idType = this._view.InfoAddressType,
                        Number = this._view.InfoPhoneNumber,
                        IdContact = this._view.SelectedContactId
                    };

                    data.Phones.AddObject(newPhone);
                    data.SaveChanges();
                }
            }
            else
            {
                Utils.DisplayError("Se debe ingresar el número y tipo de teléfono para agregar.");
            }
        }
        public void EditPhone()
        {
            if (this._view.InfoPhoneType != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var phone = (from p in data.Phones
                                 where p.IdContact == this._view.SelectedContactId &&
                                 p.idType == this._view.InfoPhoneType
                                 select p).Single();

                    phone.Number = this._view.InfoPhoneNumber;
                    phone.idType = this._view.InfoPhoneType;

                    data.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                }
            }
            else 
            {
                Utils.DisplayError("Se debe seleccionar un teléfono para modificar.");
            }
        }

        public void AddEmail()
        {
            if (this._view.InfoEmailType != -1 && this._view.InfoEmailAddress != String.Empty)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var newEmail = new Email()
                    {
                        IdType = this._view.InfoEmailType,
                        Email1 = this._view.InfoEmailAddress,
                        IdContact = this._view.SelectedContactId
                    };

                    data.Emails.AddObject(newEmail);
                    data.SaveChanges();
                }
            }
            else
            {
                Utils.DisplayError("Se debe completar la dirección de email y el tipo antes de agregar.");
            }
        }
        public void EditEmail()
        {
            if (this._view.InfoEmailType != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var email = (from em in data.Emails
                                 where em.IdContact == this._view.SelectedContactId &&
                                 em.IdType == this._view.InfoEmailType
                                 select em).Single();

                    email.Email1 = this._view.InfoEmailAddress;
                    email.IdType = this._view.InfoEmailType;

                    data.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                }
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar un email para modificar.");
            }
        }

        public void RemoveAddress()
        {
            if (this._view.InfoAddressType != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var address = (from a in data.Addresses
                                   where a.IdType == this._view.InfoAddressType &&
                                   a.IdContact == this._view.SelectedContactId
                                   select a).Single();

                    data.Addresses.DeleteObject(address);
                    data.SaveChanges();
                }
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar una dirección para eliminar.");
            }
        }

        public void RemovePhone()
        {
            if (this._view.InfoPhoneType != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var phone = (from p in data.Phones
                                 where p.IdContact == this._view.SelectedContactId &&
                                 p.idType == this._view.InfoPhoneType
                                 select p).Single();

                    data.Phones.DeleteObject(phone);

                    data.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                }
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar un teléfono para eliminar.");
            }
        }
        public void RemoveEmail()
        {
            if (this._view.InfoEmailType != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var email = (from em in data.Emails
                                 where em.IdContact == this._view.SelectedContactId &&
                                 em.IdType == this._view.InfoEmailType
                                 select em).Single();

                    data.Emails.DeleteObject(email);

                    data.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                }
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar un email para eliminar.");
            }
        }



        public void AddContact()
        {
            this._view.SelectedInfoContactId = -1;
            this._view.InfoContactBirthDate = DateTime.Now;
            this._view.InfoContactComments = string.Empty;
            this._view.InfoContactFirstName = string.Empty;
            this._view.InfoContactLastName = string.Empty;
            this._view.InfoContactImage = null;
            this._view.InfoAddresses = new List<UIAddress>();
            this._view.InfoEmails = new List<UIEmail>();
            this._view.InfoPhones = new List<UIPhone>();
            this._view.InfoGroups = new List<UIGroup>();
            EnableContactInfoLinks();
        }

        private void EnableContactInfoLinks()
        {
            var enable = (this._view.SelectedInfoContactId != -1);
            this._view.EnableAddressAdd = enable;
            this._view.EnableAddressModify = enable;
            this._view.EnableAddressRemove = enable;
            this._view.EnableEmailAdd = enable;
            this._view.EnableEmailModify = enable;
            this._view.EnableEmailRemove = enable;
            this._view.EnablePhoneAdd = enable;
            this._view.EnablePhoneModify = enable;
            this._view.EnablePhoneRemove = enable;
        }


        public void AddGroupToContact()
        {
            if (this._view.SelectedInfoGroup != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var group = (from g in data.Groups
                                 where g.Id == this._view.SelectedInfoGroup
                                 select g).Single();

                    var contact = (from c in data.Contacts
                                   where c.Id == this._view.SelectedInfoContactId
                                   select c).Single();

                    contact.Groups.Add(group);

                    data.SaveChanges();

                }
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar un grupo para agregarlo.");
            }
        }

        public void RemoveGroupFromContact()
        {
            if (this._view.SelectedInfoGroup != -1)
            {
                using (var data = new DotNetPractico1Entities())
                {
                    var group = (from g in data.Groups
                                 where g.Id == this._view.SelectedInfoGroup
                                 select g).Single();

                    var contact = (from c in data.Contacts
                                   where c.Id == this._view.SelectedInfoContactId
                                   select c).Single();

                    contact.Groups.Remove(group);

                    data.SaveChanges();

                }
            }
            else
            {
                Utils.DisplayError("Se debe seleccionar un grupo para eliminar.");
            }
        }

        public void RemoveContact()
        {
            using (var data = new DotNetPractico1Entities())
            {
                var contact = (from c in data.Contacts
                               where c.Id == this._view.SelectedInfoContactId
                               select c).Single();
                data.Contacts.DeleteObject(contact);
                data.SaveChanges();
            }

        }

        public void ExportContacts()
        {
            // Crear el archivo csv
            StreamWriter writer = new StreamWriter(this._view.SaveCSVFileName, false);

            foreach (var contact in this._view.Contacts)
            {
                string line = string.Format("{0},{1},{2},{3}", contact.BirthDate.ToShortDateString(), contact.Comments, contact.FirstName, contact.LastName);

                writer.WriteLine(line);
            }
            writer.Close();
        }

        public void RemoveGroup()
        {
            using (var data = new DotNetPractico1Entities())
            {
                var group = (from g in data.Groups
                             where g.Id == this._view.SelectedGroup
                             select g).Single();

               

                data.Groups.DeleteObject(group);

                data.SaveChanges();

            }
        }
    }
}
